package cn.tedu.eb_film.service.impl;

import cn.tedu.eb_film.ex.ServiceException;
import cn.tedu.eb_film.mapper.CinemaHallMapper;
import cn.tedu.eb_film.mapper.CinemaScheduleMapper;
import cn.tedu.eb_film.mapper.MovieMapper;
import cn.tedu.eb_film.pojo.dto.CinemaScheduleAddNewDTO;
import cn.tedu.eb_film.pojo.dto.CinemaScheduleEditDTO;
import cn.tedu.eb_film.pojo.dto.CinemaScheduleUpdateInfoDTO;
import cn.tedu.eb_film.pojo.entity.CinemaHall;
import cn.tedu.eb_film.pojo.entity.CinemaSchedule;
import cn.tedu.eb_film.pojo.vo.*;
import cn.tedu.eb_film.service.CinemaScheduleService;
import cn.tedu.eb_film.service.MovieService;
import cn.tedu.eb_film.utils.ServiceCode;
import cn.tedu.eb_film.utils.StateCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 场次服务实现类
 *
 * @author zhongcongwen
 * @since 2023/3/21 19:37
 */
@Slf4j
@Service
public class CinemaScheduleServiceImpl implements CinemaScheduleService {
    @Autowired
    private CinemaScheduleMapper cinemaScheduleMapper;
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private CinemaHallMapper cinemaHallMapper;


    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public void addNew(CinemaScheduleAddNewDTO CinemaScheduleAddNewDTO) {
        log.debug("开始处理场次新增");
        final CinemaScheduleStandardVO CinemaScheduleStandardVO = cinemaScheduleMapper.getStandardById(CinemaScheduleAddNewDTO.getId());
        if (CinemaScheduleStandardVO != null) {
            String message = "新增失败,该时间场次已经存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        CinemaSchedule CinemaSchedule = new CinemaSchedule();
        BeanUtils.copyProperties(CinemaScheduleAddNewDTO, CinemaSchedule);
        CinemaSchedule.setCreateTime(LocalDateTime.now());
        CinemaSchedule.setUpdateTime(LocalDateTime.now());

        final int rows = cinemaScheduleMapper.insert(CinemaSchedule);
        if (rows != 1) {
            String message = "新增失败,新增场次数据不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        log.debug("新增完成");
    }

    @Override
    public void addNews(List<CinemaScheduleAddNewDTO> CinemaScheduleAddNewDTOS) {
        log.debug("开始批量处理处理场次新增");

        CinemaScheduleAddNewDTOS.forEach(addNew -> {
            CinemaScheduleStandardVO standardVO = cinemaScheduleMapper.getStandardById(addNew.getId());
            if (standardVO != null) {
                String message = "新增失败,该时间场次已经存在";
                log.warn(message + "场次为{}", addNew);
                throw new ServiceException(ServiceCode.ERROR_INSERT, message);
            }
        });

        List<CinemaSchedule> CinemaSchedules = new ArrayList<>();
        CinemaScheduleAddNewDTOS.forEach(addNew -> {
            CinemaSchedule CinemaSchedule = new CinemaSchedule();
            BeanUtils.copyProperties(addNew, CinemaSchedule);
            CinemaSchedule.setCreateTime(LocalDateTime.now());
            CinemaSchedule.setCreateTime(LocalDateTime.now());
            CinemaSchedules.add(CinemaSchedule);
        });
        log.debug("开始插入到数据库");
        int rows = cinemaScheduleMapper.insertBatch(CinemaSchedules);
        if (rows <= 1) {
            String message = "新增失败,新增场次数据不大于1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
        log.debug("新增完成");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始根据id删除场次数据");
        final CinemaScheduleStandardVO standardVO = cinemaScheduleMapper.getStandardById(id);
        if (standardVO == null) {
            String message = "删除失败,该时间场次不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        if (standardVO.getState().equals(StateCode.STATE_DISABLE.getValue())) {
            String message = "删除失败,该时间场次被禁用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        if (standardVO.getState().equals(StateCode.STATE_DELETE.getValue())) {
            String message = "删除失败,该时间场次不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        final int rows = cinemaScheduleMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除失败,该时间场次数据不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        log.debug("删除成功");
    }

    @Override
    public void deleteByIds(List<Long> id) {
        log.debug("开始批量删除数据");
        id.forEach(item -> {
            final CinemaScheduleStandardVO standardVO = cinemaScheduleMapper.getStandardById(item);
            if (standardVO == null) {
                String message = "删除失败,该场次不存在";
                log.warn(message + "场次id为{}", item);
                throw new ServiceException(ServiceCode.ERROR_DELETE, message);
            }

            if (standardVO.getState().equals(StateCode.STATE_DISABLE.getValue())) {
                String message = "删除失败,该场次被禁用";
                log.warn(message + "场次id为{}", item);
                throw new ServiceException(ServiceCode.ERROR_DELETE, message);
            }
            if (standardVO.getState().equals(StateCode.STATE_DELETE.getValue())) {
                String message = "删除失败,该场次已被删除";
                log.warn(message + "场次id为{}", item);
                throw new ServiceException(ServiceCode.ERROR_DELETE, message);
            }
        });

        List<Long> ids = new ArrayList<>(id);

        final int rows = cinemaScheduleMapper.deleteByIds(ids);
        if (rows <= 1) {
            String message = "删除失败,该场次数据不大于1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        log.debug("删除成功");
    }

    @Override
    public Long count() {
        log.debug("开始统计总数量");
        return cinemaScheduleMapper.count();
    }

    @Override
    public CinemaScheduleStandardVO getCinemaScheduleById(Long id) {
        log.debug("开始处理根据Id查询数据");
        final CinemaScheduleStandardVO standardVO = cinemaScheduleMapper.getStandardById(id);
        if (standardVO == null) {
            String message = "查询失败,该数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_SELECT, message);
        }

        if (standardVO.getState().equals(StateCode.STATE_DELETE.getValue())) {
            String message = "查询失败,该数据已删除";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_SELECT, message);
        }
        return standardVO;
    }

    @Override
    public List<CinemaScheduleListItemVO> list() {
        log.debug("开始处理查询所有数据");
        List<CinemaScheduleListItemVO> list = cinemaScheduleMapper.list();
        list.removeIf(hall -> hall.getState().equals(StateCode.STATE_DELETE.getValue()));


        return list;
    }

    @Override
    public List<CinemaScheduleListItemVO> listByCinemaHallId(Long cinemaId,Integer state) {
        List<CinemaScheduleListItemVO> cinemaScheduleList = cinemaScheduleMapper.listByCinemaHallId(cinemaId,state);
        cinemaScheduleList.removeIf(hall -> StateCode.STATE_DELETE.getValue().equals(hall.getState()));
        return cinemaScheduleList;
    }


    @Override
    public void update(CinemaScheduleUpdateInfoDTO CinemaScheduleUpdateDTO) {
        log.debug("开始修改编辑数据");
        final CinemaScheduleStandardVO standardVOById = cinemaScheduleMapper.getStandardById(CinemaScheduleUpdateDTO.getId());
        if (standardVOById == null) {
            String message = "修改失败,该数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        if (standardVOById.equals(StateCode.STATE_DELETE.getValue())) {
            String message = "修改失败,该数据已被删除";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        CinemaSchedule CinemaSchedule = new CinemaSchedule();
        BeanUtils.copyProperties(CinemaScheduleUpdateDTO, CinemaSchedule);
        CinemaSchedule.setUpdateTime(LocalDateTime.now());

        final int rows = cinemaScheduleMapper.update(CinemaSchedule);
        if (rows != 1) {
            String message = "修改失败,修改条数不为1";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        log.debug("修改成功");
    }

    public void updateEnableById(Long id, Integer enable) {
        CinemaScheduleStandardVO queryResult = cinemaScheduleMapper.getStandardById(id);
        if (queryResult == null ||
                queryResult.getState().equals(StateCode.STATE_DELETE.getValue())) {
            String message = ENABLE_TEXT[enable] + "的场次数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        if (enable.equals(queryResult.getState())) {
            String message = ENABLE_TEXT[enable] + "失败,修改的目标状态与目前一致";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        CinemaSchedule update = new CinemaSchedule();
        update.setId(queryResult.getId());
        update.setState(enable);
        int rows = cinemaScheduleMapper.update(update);
        if (rows != 1) {
            String message = "修改失败,服务器忙,请稍后尝试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void editSchedule(CinemaScheduleEditDTO cinemaScheduleEditDTO) {
        CinemaScheduleStandardVO schedule =
                cinemaScheduleMapper.getStandardById(cinemaScheduleEditDTO.getId());
        if (schedule == null || schedule.getState().equals(StateCode.STATE_DELETE.getValue())) {
            String message = "修改失败,该场次不存在了";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }


        MovieStandardVO movie =
                movieMapper.getStandardById(cinemaScheduleEditDTO.getMovieId());

        if (movie == null || movie.getState().equals(StateCode.STATE_DELETE.getValue())) {
            String message = "修改失败,该电影不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }


        CinemaSchedule cinemaSchedule = new CinemaSchedule();

        cinemaSchedule.setMovieId(cinemaScheduleEditDTO.getMovieId());
        cinemaSchedule.setId(cinemaScheduleEditDTO.getId());
        cinemaSchedule.setMoviePrice(cinemaScheduleEditDTO.getMoviePrice());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String dateFormat = format.format(cinemaScheduleEditDTO.getMovieStartTime());
        LocalDateTime localDateTime = LocalDateTime.parse(dateFormat, DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss"));
        /* 更新时间*/
        cinemaSchedule.setMovieStartTime(localDateTime);
        cinemaScheduleMapper.update(cinemaSchedule);

    }
}
